import {reqGetUser, reqUpdateUser} from '../../api'
import render from './index.art'

const updateForm = document.getElementById('updateForm')

/* 
  读取query参数指定参数名的值
*/
function getQueryValue(name) {
  var str = location.href.split('?');
  var query = str[1];
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == name) {
      return pair[1];
    }
  }
}

/* 
获取要修改的用户信息显示
*/
async function getUser() {
  const id = getQueryValue('id')
  const result = await reqGetUser(id)
  const user = result.data
  const html = render({user})
  updateForm.innerHTML = html

  handlePreview()
}

/* 
处理图片预览
*/
function handlePreview () {
  document.getElementById('profile').onchange = (e) => {
    const fileReader = new FileReader()
    const file = e.target.files[0]
    console.log(e.target.files)
    fileReader.readAsDataURL(file)
    fileReader.onload = () => {
      const profile = fileReader.result
      document.getElementById('profileImg').src = profile
    }
  }
}

/* 
绑定提交事件
*/
updateForm.onsubmit = async (e) => {
  e.preventDefault()

  const formData = new FormData(updateForm)
  await reqUpdateUser(formData)
  window.location = '/users.html'
}

getUser()